//
//  977. 有序数组的平方.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/15.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution977 {
    // 题目已经明确了是新数组，所以不需要思考在原有数组的基础上操作
    // 两边的值一定是最大的(这个是非常关键的)，所以只需要比较两边的值谁大，就将谁添加进数组里
    func sortedSquares(_ nums: [Int]) -> [Int] {
        var left = 0
        var right = nums.count - 1
        var result: [Int] = []
        while left <= right {
            let leftS = nums[left] * nums[left]
            let rightS = nums[right] * nums[right]
            if leftS < rightS {
                result.insert(rightS, at: 0)
                right -= 1
            } else {
                result.insert(leftS, at: 0)
                left += 1
            }
        }
        return result
    }
    static func test() {
        let solution = Solution977()
        let nums =  [-4,-1,0,3,10]
        let result =  solution.sortedSquares(nums)
        print(result)
    }
}
